//
//  GKVideoCaptureController.m
//  视频采集
//
//  Created by Apple on 16/11/1.
//  Copyright © 2016年 郭凯. All rights reserved.
//

#import "GKVideoCaptureController.h"
#import "GKRecordEncode.h"
#import "GKRecordProgressView.h"
#import "GKRecordTool.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
typedef NS_ENUM(NSUInteger, UploadVieoStyle) {
    VideoRecord = 0,
    VideoLocation,
};


@interface GKVideoCaptureController ()<GKRecordToolDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *flashLightBT;
@property (weak, nonatomic) IBOutlet UIButton *changeCameraBT;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UIButton *recordBt;
@property (weak, nonatomic) IBOutlet UIButton *locationVideoBT;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewTop;
@property (weak, nonatomic) IBOutlet GKRecordProgressView *progressView;
@property (strong, nonatomic) GKRecordTool         *recordEngine;
@property (assign, nonatomic) BOOL                    allowRecord;//允许录制
@property (assign, nonatomic) UploadVieoStyle         videoStyle;//视频的类型
@property (strong, nonatomic) UIImagePickerController *moviePicker;//视频选择器
@property (strong, nonatomic) MPMoviePlayerViewController *playerVC;
@property (strong, nonatomic) IBOutlet UIView *videoView;
@property (strong, nonatomic) IBOutlet UIButton *indicatorView;
//记录上次的旋转方向
@property (nonatomic,assign) NSInteger orientation ;
@end

@implementation GKVideoCaptureController

- (UIImagePickerController *)moviePicker {
    if (_moviePicker == nil) {
        _moviePicker = [[UIImagePickerController alloc] init];
        _moviePicker.delegate = self;
        _moviePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _moviePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    }
    return _moviePicker;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.recordEngine shutdown];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_recordEngine == nil) {
        [self.recordEngine previewLayer].frame = self.videoView.bounds;
        [self.videoView.layer insertSublayer:[self.recordEngine previewLayer] atIndex:0];
    }
    [self.recordEngine startUp];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.allowRecord = YES;
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(EnterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

-(void)screenOrientationDidChange:(NSNotification *)infor{
    NSLog(@"%ld",[[UIDevice currentDevice] orientation]);
    switch ([[UIDevice currentDevice] orientation]) {
        case 0://垂直朝上
            [self setUpRotation:0];
            break;
        case 1://垂直朝上
            [self setUpRotation:0];
            break;
        case 4://向右旋转
            [self setUpRotation:-M_PI_2];
            break;
        case 3://向左旋转
            [self setUpRotation:M_PI_2];
            break;
        case 2://垂直朝下
        {
            CGFloat angle = 0;
            if (self.orientation==3) {
                angle = M_PI;
            }else{
                angle = -M_PI;
            }
              [self setUpRotation:angle];
        }
            break;
        case 5://平躺屏幕朝上
             [self setUpRotation:0];
            break;
        default:
            break;
    }
    
    self.orientation = [[UIDevice currentDevice] orientation];
}

// 设置控件的旋转方向
-(void)setUpRotation:(CGFloat)angle{
    CGAffineTransform trans = CGAffineTransformMakeRotation(0);
    [UIView animateWithDuration:0.25 animations:^{
        self.deleteBtn.transform =CGAffineTransformRotate(trans, angle);
        self.locationVideoBT.transform =CGAffineTransformRotate(trans, angle);
    }];
}

//进入后台
-(void)EnterBackgroundNotification{
    NSLog(@"进入后台");
      [self.recordEngine stopCaptureHandlerIsSave:NO Image:^(UIImage *movieImage) {
          self.recordBt.selected = NO;
      }];
}
//根据状态调整view的展示情况
- (void)adjustViewFrame {
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        if (self.recordBt.selected) {
            self.topViewTop.constant = -64;
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        }else {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
            self.topViewTop.constant = 0;
        }
        [self.view layoutIfNeeded];
    } completion:nil];
}

#pragma mark - set、get方法
- (GKRecordTool *)recordEngine {
    if (_recordEngine == nil) {
        _recordEngine = [[GKRecordTool alloc] init];
        _recordEngine.delegate = self;
    }
    
    return _recordEngine;
}

#pragma mark - Apple相册选择代理
////选择了某个照片的回调函数/代理回调
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    NSLog(@"当前的信息 = %@",info);
//    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]) {
//        //获取视频的名称
//        NSString * videoPath=[NSString stringWithFormat:@"%@",[info objectForKey:UIImagePickerControllerMediaURL]];
//        NSRange range =[videoPath rangeOfString:@"trim."];//匹配得到的下标
//        NSString *content=[videoPath substringFromIndex:range.location+5];
//        //视频的后缀
//        NSRange rangeSuffix=[content rangeOfString:@"."];
//        NSString * suffixName=[content substringFromIndex:rangeSuffix.location+1];
//        //如果视频是mov格式的则转为MP4的
//        if ([suffixName isEqualToString:@"MOV"]) {
//            NSURL *videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
//            __weak typeof(self) weakSelf = self;
//            //将视频转换成MP4格式
//            [self.recordEngine changeMovToMp4:videoUrl dataBlock:^(UIImage *movieImage) {
//                
//                [weakSelf.moviePicker dismissViewControllerAnimated:YES completion:^{
//                    weakSelf.playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:weakSelf.recordEngine.videoPath]];
//                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:[weakSelf.playerVC moviePlayer]];
//                    [[weakSelf.playerVC moviePlayer] prepareToPlay];
//                    
//                    [weakSelf presentMoviePlayerViewControllerAnimated:weakSelf.playerVC];
//                    [[weakSelf.playerVC moviePlayer] play];
//                }];
//            }];
//        }
//    }
//}

#pragma mark - 进度条代理方法
- (void)recordProgress:(CGFloat)progress {
    if (progress >= 1) {
        [self recordAction:self.recordBt];
        self.allowRecord = NO;
    }
    self.progressView.progress = progress;
}

#pragma mark - 各种点击事件
//返回点击事件
- (IBAction)dismissAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//开关闪光灯
- (IBAction)flashLightAction:(id)sender {
    if (self.changeCameraBT.selected == NO) {
        self.flashLightBT.selected = !self.flashLightBT.selected;
        if (self.flashLightBT.selected == YES) {
            [self.recordEngine openFlashLight];
        }else {
            [self.recordEngine closeFlashLight];
        }
    }
}

//切换前后摄像头
- (IBAction)changeCameraAction:(id)sender {
    self.changeCameraBT.selected = !self.changeCameraBT.selected;
    if (self.changeCameraBT.selected == YES) {
        //前置摄像头
        [self.recordEngine closeFlashLight];
        self.flashLightBT.selected = NO;
        [self.recordEngine changeCameraInputDeviceisFront:YES];
    }else {
        [self.recordEngine changeCameraInputDeviceisFront:NO];
    }
}

////录制下一步点击事件
//
//- (IBAction)recordNextAction:(id)sender {
//    return;
//    if (_recordEngine.videoPath.length > 0) {
//        __weak typeof(self) weakSelf = self;
//          [self.recordEngine stopCaptureHandlerIsSave:YES Image:^(UIImage *movieImage) {
//              weakSelf.videoImage = movieImage;
//              [self playRecordVideo];
//        }];
//    }else {
//        NSLog(@"请先录制视频~");
//        self.indicatorView.hidden = NO;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//             self.indicatorView.hidden = YES;
//        });
//    }
//}


//// 预览播放视频
//-(void)playRecordVideo{
//    __weak typeof(self) weakSelf = self;
//    self.playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:weakSelf.recordEngine.videoPath]];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:[weakSelf.playerVC moviePlayer]];
//    [[weakSelf.playerVC moviePlayer] prepareToPlay];
//    [weakSelf presentMoviePlayerViewControllerAnimated:weakSelf.playerVC];
//    [[weakSelf.playerVC moviePlayer] play];
//
//}
//当点击Done按键或者播放完毕时调用此函数
- (void)playVideoFinished:(NSNotification *)theNotification {
    MPMoviePlayerController *player = [theNotification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    [player stop];
    [self.playerVC dismissMoviePlayerViewControllerAnimated];
    self.playerVC = nil;
    self.allowRecord = NO;
}

//点击上传视频
- (IBAction)locationVideoAction:(id)sender {
   
    NSLog(@"当前的状态 = %d", self.recordEngine.isCapturing);
    if (!self.recordEngine.isCapturing) {
             self.indicatorView.hidden = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             self.indicatorView.hidden = YES;
        });
        return;
    }
    
    [self.recordEngine stopCaptureHandlerIsSave:YES Image:^(UIImage *movieImage) {
         self.videoFristImage(movieImage);
         [self dismissAction:nil];
       }];
}

//开始和暂停录制事件
- (IBAction)recordAction:(UIButton *)sender {
    if (self.allowRecord){
        self.indicatorView.hidden = YES;
        self.videoStyle = VideoRecord;
        self.recordBt.selected = !self.recordBt.selected;
        if (self.recordBt.selected) {
            if (self.recordEngine.isCapturing) {
                NSLog(@"恢复录制");
                [self.recordEngine resumeCapture];
            }else {
                [self.recordEngine startCapture];
                NSLog(@"开始录制");
            }
        }else {
            [self.recordEngine pauseCapture];
        }
        [self adjustViewFrame];
    }
}
//删除录制的视频
- (IBAction)deleteRecordVideo:(id)sender {
    if (self.recordBt.selected) return;
      self.allowRecord = YES;
      [self adjustViewFrame];
        [self.recordEngine stopCaptureHandlerIsSave:NO Image:^(UIImage *movieImage) {
            NSLog(@"删除成功 = %@",movieImage);
            //将进度条清除
            self.progressView.progress = 0.0;
        }];
    
}

- (void)dealloc {
    _recordEngine = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"挂");
}

@end
